package org.ch02.test00.demo08.teacherWork;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.ch02.test00.demo08.myWork.DbUtil;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

/**
 * @author CSY
 * @date 2025 - 03 - 21
 */
public class DruidUtil {
    private static DataSource dataSource;

    public static DataSource getDataSource() {
        if (dataSource == null) {
            initDataSource();
        }
        return dataSource;
    }

    public static void initDataSource() {
        Properties prop = new Properties();
        try {
            prop.load(DbUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static ResultSet executeQuery(String sql, Object... params) {
        Connection conn = getConnection();
        ResultSet rs = null;
        PreparedStatement psmt = null;
        try {
            psmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                psmt.setObject(i + 1, params[i]);
            }
            rs = psmt.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }

    public static void close(ResultSet rs, Statement state,Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(state != null){
            try {
                state.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
